// map init value
var mapwidth;
var mapheight;
var g_WorldX = 0.0;							
var g_WorldY = 0.0;
var g_ScreenX;									
var g_ScreenY;
var g_Scale = 1.0; 	

var currentScale = 0.0;	
var prev_Scale = 0.0;

var oldcursor = "default";
// mode conditional flag 
var isDrawBoxBand = false; // zoomin zommout box band
var isPanning = false; // pan move
var isMeasure = false; // dist

// box Coordinate init;
var startX = 0;
var startY = 0;
var endX = 0;
var endY = 0;

//hist idex 
var historyIndex = 0 ;
var requestHistIdex = -1 ;

var mapCanvas = null;
var mapCanvas2 = null;
function onError(obj) {
	alert("Error " + obj.status + " -- " + obj.statusText);
}
function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y)
		curtop += obj.y;
	return curtop;
}
function getMapCenter(minx, miny, maxx, maxy) {
	dminx = eval(minx);
	dminy = eval(miny);
	dmaxx = eval(maxx);
	dmaxy = eval(maxy);

  g_WorldX = dminx + ((dmaxx - dminx)/2);
  g_WorldY = dminy + ((dmaxy - dminy)/2);
}

function initMapCoordinate(minx, miny, maxx, maxy, screenx, screeny) {
	dScaleX = 0.0;
	dScaleY = 0.0;

	if ( ( ( maxx - minx ) == 0 ) || ( (maxy - miny) == 0 ) ) return false;

	g_WorldX = (eval(minx) + eval(maxx)) / 2;
	g_WorldY = (eval(miny) + eval(maxy)) / 2;

	dScaleX = (screenx*2) / (maxx - minx);
	dScaleY = (screeny*2) / (maxy - miny);

	if ( dScaleX > dScaleY ) g_Scale = dScaleY;
	else g_Scale = dScaleX;
}

function worldToScreen(wx, wy, outPoint) {
	outPoint[0] = Math.round((wx - g_WorldX) * g_Scale + g_ScreenX);
	outPoint[1] = Math.round((g_WorldY - wy) * g_Scale + g_ScreenY);
}

function screenToWorld(sx, sy, outPoint) {
	outPoint[0] = g_WorldX + ((sx - g_ScreenX) / g_Scale);
	outPoint[1] = g_WorldY - ((sy - g_ScreenY) / g_Scale);
}

function setStartPoint(){
	if (window.ie) {
		startX = event.clientX-2;
		startY = event.clientY-2;
	}
	else {
		startX = e.pageX;
		startY = e.pageY;
	}
	startX -= findPosX($('container'));
	startY -= findPosY($('container'));	
	if (startX < 0) startX = 0;
	if (startY < 0) startY = 0;
}

function setEndPoint(){
	if (window.ie) {
		endX = event.clientX - 2;
		endY = event.clientY - 2;
	}
	else {
		endX = e.pageX;
		endY = e.pageY;
	}
	endX -=  findPosX($('container'));
	endY -=  findPosY($('container'));
	if (endX < 0) endX = 0;
	if (endY < 0) endY = 0;
}


function finishZoomIn() {
	var PosLT = new Array(); // Left Top
	var PosRB = new Array(); // Right Bottom
	screenToWorld(startX, startY, PosLT);
	screenToWorld(endX, endY, PosRB);

	initMapCoordinate(PosLT[0], PosLT[1], PosRB[0], PosRB[1], g_ScreenX , g_ScreenY);
	getMapImage(PosLT[0], PosLT[1], PosRB[0], PosRB[1]);
	mapCanvas.clear();
}


function finishZoomOut() {
	var PosLT = new Array();
	var PosRB = new Array();
	screenToWorld(startX, startY, PosLT);
	screenToWorld(endX, endY, PosRB);

	minx = eval(PosLT[0]) - Math.abs( eval(PosLT[0]) - eval(currMinX) )*2;
    miny = eval(PosLT[1]) + Math.abs( eval(PosLT[1]) - eval(currMinY) )*2;
	maxx = eval(PosRB[0]) + Math.abs( eval(PosRB[0]) - eval(currMaxX) )*2;
    maxy = eval(PosRB[1]) - Math.abs( eval(PosRB[1]) - eval(currMaxY) )*2;

	initMapCoordinate(minx, miny, maxx, maxy, g_ScreenX, g_ScreenY);
	getMapImage(minx, miny, maxx, maxy);
	mapCanvas.clear();
}

function finishPanning() {
	pPos1 = new Array();
	pPos2 = new Array();
	nX = eval(startX) - eval(endX);
	nY = eval(startY) - eval(endY);

	screenToWorld(nX, nY, pPos1);
	screenToWorld(eval(nX + mapwidth), eval(nY + mapheight), pPos2);

	initMapCoordinate(pPos1[0], pPos1[1], pPos2[0], pPos2[1], g_ScreenX , g_ScreenY);
	getMapImage(pPos1[0], pPos1[1], pPos2[0], pPos2[1]);
}
function finishPolyLine(evt){
	//mapCanvas2.clear();
	mapCanvas.clear();
	var t = 'end polyline';
	
	var worldXY = new Array(); 
	var x1, x2, y1, y2;
	var totalDist = 0 ;
	for(var i=0;i<idx;i++){
		// worldXY = new Array();	
		//screenToWorld(XPoints[i], YPoints[i], worldXY);
		if(i>0){
		screenToWorld(XPoints[i-1], YPoints[i-1], worldXY);
		x1 = worldXY[0];
		y1 = worldXY[1];
		screenToWorld(XPoints[i], YPoints[i], worldXY);
		x2 = worldXY[0];
		y2 = worldXY[1];
		totalDist += distance(x1,y1,x2,y2);
		}
	}
	
	t += '' + totalDist+'<br>';
	var posx = 0;
	var posy = 0;
	if (window.ie) {
		posx = event.clientX ;
		posy = event.clientY ;
	}
	else {
		posx = e.pageX;
		posy = e.pageY;
	}
	
	
	win2.setStyles({'top':posy+'px','left':posx+'px'});
	win2.setContent(t);
	win2.setStatus(posx + ',' + posy);
	win2.show();
//	$('debugbox').innerHTML  = t;
}

function finishPloygon(){
	mapCanvas.clear();
}
function refresh(){
	$('mainmap').style.cursor= "progress"; 
	var mapValues = $('mainmap').getCoordinates(); 
	var url = 'getImageMap.do';
	req ='';// 'screenWidth='+mapValues.width+'&screenHeight='+mapValues.height;
	ajaxMapFunc(url, req, onGetMapImage );
}

	var idx = 0 ;
	var temp = '';
function drawPolyline() {	
	//$('debugbox').innerHTML  =XPoints[idx-1]+','+XPoints[idx-1]+','+XPoints[idx]+','+XPoints[idx];
	//mapCanvas2.clear();
	mapCanvas2.drawLine(XPoints[idx-1],YPoints[idx-1],XPoints[idx],YPoints[idx]);
	mapCanvas2.paint(); 
}

function drawPolylineTemp() {
//	$('debugbox').innerHTML  ='isDrawPolyLine ' + isDrawPolyLine + ' : ' + XPoints[idx-1]+','+XPoints[idx-1]+','+XPoints[idx]+','+XPoints[idx];
	mapCanvas.clear();
	mapCanvas.drawLine(startX,startY,endX,endY);
	mapCanvas.paint(); 
}

function drawPolygon(){
	mapCanvas.clear();
	mapCanvas.drawPolygon([startX, startX, endX, endX, startX], [startY, endY, endY, startY, startY]); 
	mapCanvas.paint();
}

function drawRubberband() {
	mapCanvas.clear();
	mapCanvas.drawPolygon([startX, startX, endX, endX, startX], [startY, endY, endY, startY, startY]); 
	mapCanvas.paint();
}

function getMapImage(minx, miny, maxx, mayy) {
	$('mainmap').setStyles({
			'cursor' : 'progress',
			'visibility' : 'hidden'
	});
	$('mapbuffer').setStyle('visibility' , 'visible');
	var mapValues = $('mainmap').getCoordinates(); 
	req = 'screenWidth='+mapValues.width+'&screenHeight='+mapValues.height;
	req +='&minX=' + minx + '&minY=' + miny + '&maxX=' + maxx + '&maxY=' + mayy;
	var url = 'getImageMap.do';
	ajaxMapFunc(url, req, onGetMapImage );
}

function onGetMapImage(responseXML) {
	if (responseXML == null ) return false;
	env = responseXML.getElementsByTagName("ENVELOPE");

	if (env == null) { alert("ENVELOPE IS NULL"); return false; }
	currMinX = env[0].getAttribute("minx");
	currMinY = env[0].getAttribute("miny");
	currMaxX = env[0].getAttribute("maxx");
	currMaxY = env[0].getAttribute("maxy");

	initMapCoordinate(currMinX, currMinY, currMaxX, currMaxY, g_ScreenX , g_ScreenY);
	getMapCenter(currMinX, currMinY, currMaxX, currMaxY);

	
	var history = responseXML.getElementsByTagName("HISTORY");
	if(history == null ) historyIndex = 0 ; 
	historyIndex = history[0].getAttribute("index");
	requestHistIdex= history[0].getAttribute("histPosIndex");
	
	img = responseXML.getElementsByTagName("OUTPUT");
	if (img == null) { alert("OUTPUT is NULL!."); return false; }
	prev_Scale = currentScale;
	currentScale =  img[0].getAttribute("scale");
	loadScaleSelect(currentScale);
	
	imgUrl = img[0].getAttribute("url");
	
	
	
	$('mainmap').setStyles({
			'background-image' :  'url('+imgUrl+')',
			'cursor' : oldcursor,
			'visibility' : 'visible'
	});
	
	$('mapbuffer').setStyles({
			'left' : 0,
			'top' :0,
			'background-image' :  'url('+imgUrl+')',
			'visibility' : 'hidden'
	});
}
var XPoints = new Array(0);
	var YPoints = new Array(0); 
	var isDrawPolyLine = false;
/**
*
*/

function contextMenuBlock(evt){
	var isBlock = false;
	if (window.ie) {
		if(event.button==2){
			isBlock = true;
		}
	}
	else {
		if (e.which==2||e.which==3){
			isBlock = true;
		}	
	}
	return isBlock;
}

function mapMouseDown(evt){
	if (maptool == null)  return false;
	switch(maptool.id) {
		case "zoomin":	
		if (isDrawBoxBand) finishZoomIn();
		isDrawBoxBand = !isDrawBoxBand;		
		break;
		case "zoomout":
		if (isDrawBoxBand)  finishZoomOut();
		isDrawBoxBand = !isDrawBoxBand;
		break;
		case "area" :
			if (isDrawBoxBand)  finishPloygon();
			isDrawBoxBand = !isDrawBoxBand;
			break;
		case "dist":	
				if(contextMenuBlock(evt)) {
					finishPolyLine(evt);
					isDrawPolyLine = false;
				}else{
					isDrawPolyLine = true;
				}
					
		break;
		case "pan":
			$('mapbuffer').setStyle('visibility','visible');
			$('mainmap').setStyle('visibility','hidden');			
			isPanning = true;
		break;
		case "beforehistory" : break;
		case "afterhistory" :break;
		case "identify" :
			identify();
		break;
		case "refresh" :break;
		default: break;
	}
	
	setStartPoint();
}

function mapMouseMove(evt){
	if (maptool == null)  return false;
	if ( (!isDrawBoxBand) && (!isPanning) &&(!isDrawPolyLine)) return false;
	setEndPoint(); 
	switch(maptool.id) {
		case "zoomin":			
			drawRubberband();
			break;
		case "zoomout":
			drawRubberband();
			break;
		break;
		case "dist":
			drawPolylineTemp();
			break;		
		case "area" :
			drawPolygon();
			break;
		case "pan":
			if ( isPanning ) {
				cl = $('container').offsetLeft;
				ct = $('container').offsetTop;
				dX = eval(endX - startX );
				dY = eval(endY - startY );
				$('mapbuffer').style.left = dX + 'px';
				$('mapbuffer').style.top = dY + 'px';
			}
			break;
		case "beforehistory" : break;
		case "afterhistory" :break;
		case "identify" :
			
		break;
		case "refresh" :break;
		default: break;
	}
}

function mapMouseUp(evt){
	if (maptool == null)  return false;
	switch(maptool.id) {
		case "zoomin":		
		break;
		case "zoomout":
		break;
		case "dist":
			if(contextMenuBlock(evt)){
			 	finishPolyLine();
			 	isDrawPolyLine = false;
			}else{
				if(idx==0){
					XPoints[idx]=startX;
					YPoints[idx]=startY;
					idx ++ ;
				}else{
					setEndPoint(); 
					if(XPoints[idx-1]!=endX && YPoints[idx-1]!=endY){
						XPoints[idx]=endX;
						YPoints[idx]=endY;
						drawPolyline();
						idx ++ ;
					}
				}	
			}
		break;
		case "pan":
			finishPanning();
			isPanning = false;
		break;
		case "beforehistory" : break;
		case "afterhistory" :break;
		case "identify" :
		break;
		case "refresh" :break;
		default: break;
	}
}


//Disable right mouse click Script
//By Maximus (maximus@nsimail.com) w/ mods by DynamicDrive
//For full source code, visit http://www.dynamicdrive.com

var message="Function Disabled!";

///////////////////////////////////
function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}

function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}

if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}

document.oncontextmenu=new Function("return false")

